﻿// Create an <option> element
function makeOption(value, text) {
    return '<option value="' + Gw.Core.Tools.HtmlEncode(value) + '">' + Gw.Core.Tools.HtmlEncode(Gw.Core.Translate(text)) + '</option>';
}

// Add runes associated to given attribute to rune dropdown lists (except the last one which will carry the Sup Vigor rune)
function addRuneAttribute(attributeName) {
    var levels = {
        "Minor": 1,
        "Major": 2,
        "Superior": 3
    };

    for (var level in levels) {
        $(".Rune").each(function(index) {
            if (index == 4) return;
            $(this).append(makeOption(level + " " + attributeName + " Rune", Gw.Core.Translate(attributeName) + " +" + levels[level]));
        });
    }
};

// Add given insignias to insignias dropdown lists
// If insignias parameter is ommitted, common insignias will be used
function addInsignias(insignias) {
    insignias = insignias || Gw.Equipment.Insignias;

    $(".Insignia").each(function() {
        for (var i in insignias) {
            var insignia = insignias[i]
            $(this).append(makeOption(insignia, insignia));
        }
    });
};

// Add an attribute to weapon dropdown list
function addWeaponAttribute(attribute) {
    $("#WeaponAttribute").append(makeOption(attribute, Gw.Core.Translate("Weapon") + ": " + Gw.Core.Translate(attribute)));
};

// Reset all input fields in "Details" panel
// Color and Shield inscription are left as is
function resetDetails() {
    $("#Template").empty().hide();
    $(".Insignia").empty();
    addInsignias()

    $("#WeaponAttribute").empty();
    
    $(".Rune").each(function(index) {
        $(this).empty();

        if (index == 4) {
            // Only Vigor Sup rune on feet armor (make it mandatory)
            $(this).append(makeOption("Superior Vigor Rune", "Superior Vigor Rune"));
            return;
        }
        
        if (index == 0) return; // Only attribute related runes on head
        
        for (var i in Gw.Equipment.Runes) {
            var rune = Gw.Equipment.Runes[i];
            $(this).append(makeOption(rune, rune));
        }
    });

    $("#TemplateDef30_5").val("");
    $("#TemplateDef305").val("");
    $("#TemplateDef20_5").val("");
    $("#TemplateDef205").val("");

    $("#Template4040").val("");
    $("#Template15_1").val("");
    $("#Template30_2").val("");
    
    $("#Template402020").val("");
    $("#Template402030").val("");
}

// Generate templates based on data in "Details" panel
function generateTemplates() {
    var configuration = new Gw.Equipment.Configuration({
        Primary: Gw.Equipment.Professions[$("#Primary").val()],
        Secondary: Gw.Equipment.Professions[$("#Secondary").val()],
        ArmorAttribute: $("#Rune0").val().match(/\w\ (.*)\ Rune/)[1],
        WeaponAttribute: $("#WeaponAttribute").val(),
        Color: $("#Color").val(),
        Armor: new Array({
            Rune: $("#Rune0").val(),
            Insignia: $("#Insignia0").val()
        },
        {
            Rune: $("#Rune1").val(),
            Insignia: $("#Insignia1").val()
        },
        {
            Rune: $("#Rune2").val(),
            Insignia: $("#Insignia2").val()
        },
        {
            Rune: $("#Rune3").val(),
            Insignia: $("#Insignia3").val()
        },
        {
            Rune: $("#Rune4").val(),
            Insignia: $("#Insignia4").val()
        })
    });

    var shieldInscription = $("#ShieldInscription").val();

    $("#TemplateDef30_5").val(configuration.getDef30_5(shieldInscription));
    $("#TemplateDef305").val(configuration.getDef305(shieldInscription));
    $("#TemplateDef20_5").val(configuration.getDef20_5(shieldInscription));
    $("#TemplateDef205").val(configuration.getDef205(shieldInscription));

    $("#Template4040").val(configuration.get4040());
    $("#Template15_1").val(configuration.get15_1());
    $("#Template30_2").val(configuration.get30_2());

    $("#Template402020").val(configuration.get402020());
    $("#Template402030").val(configuration.get402030());
};

$(function() {
    // Interface customization
    if (Gw.Core.Tools.QueryString['detail'] == 'no')
    {
        $(".EquipmentDetail").hide();
    }

    if (Gw.Core.Tools.QueryString['manual'] == 'yes')
    {
        $("#ManualSelection").show();
    }

    // Translations
    Gw.Core.Language = Gw.Core.Tools.QueryString['language'] || 'fr';

    Gw.Core.Translate(
        ["Skill Template", "Equipment", "Process", "--- Primary Profession ---", "--- Secondary Profession ---"],
        ["Modèle de compétences", "Equipement", "Traiter", "--- Profession Primaire ---", "--- Profession Secondaire ---"], 'fr'
    );

    Gw.Core.Translate(
        ["Insignias", "Runes", "Other", "Head", "Chest", "Hands", "Legs", "Feet", "Shield", "Weapon", "Superior Vigor Rune"],
        ["Insignes", "Runes", "Autre", "Tête", "Torse", "Mains", "Jambes", "Pieds", "Bouclier", "Arme", "Santé +50"], 'fr'
    );

    var shieldInscriptions = ["The Riddle of Steel Inscription", "Sleep Now in the Fire Inscription", "Riders on the Storm Inscription", "Not the Face Inscription", "Leaf on the Wind Inscription", "Through Thick and Thin Inscription", "Like a Rolling Stone Inscription", "Swift as the Wind Inscription", "I Can See Clearly Now Inscription", "Only the Strong Survive Inscription", "Soundness of Mind Inscription", "Strength of Body Inscription", "Pure of Heart Inscription", "Fear Cuts Deeper Inscription", "Cast out the Unclean Inscription", "Master of My Domain Inscription", "Luck of the Draw Inscription", "Nothing to Fear Inscription", "Run For Your Life Inscription", "Sheltered By Faith Inscription"];
    Gw.Core.Translate(shieldInscriptions, ["+10/Dégâts tranchants", "+10/Dégâts de feu", "+10/Dégâts de foudre", "+10/Dégâts cotondants", "+10/Dégâts de froid", "+10/Dégâts perforants", "+10/Dégâts de terre", "Infirmité -20%", "Aveuglement -20%","Faiblesse -20%", "Stupeur -20%", "Blessure Profonde -20%", "Poison -20%", "Saignement -20%", "Maladie -20%", "Caracteristique +1/20%","Dégâts -5/20%", "Dégâts -3/Maléfice", "Dégâts -2/Pose", "Dégâts -2/Enchantement"], 'fr');

    Gw.Core.Translate(
        ["Shield/Spear", "Focus/Wand", "Staff"],
        ["Bouclier/Javelot", "Focus/Baguette", "Bâton"], 'fr'
    );

    $("legend, label, option").each(function() {
        $(this).html(Gw.Core.Translate($(this).html()));
    });

    $("input").each(function() {
        $(this).val(Gw.Core.Translate($(this).val()));
    });

    // Auto-select text when template text boxes get focus
    $(".TemplateCode").focus(function() {
        this.select();
    });

    window.AutomaticTemplateGeneration = false;
    
    $("#EquipmentDetail select").change(function() {
        if (window.AutomaticTemplateGeneration) generateTemplates();
    });

    for (var i in shieldInscriptions)
    {
        var inscription = shieldInscriptions[i];
        $("#ShieldInscription").append(makeOption(inscription, Gw.Core.Translate("Shield") + ": " + Gw.Core.Translate(inscription)));
    }

    for (var i in Gw.Equipment.Colors)
    {
        var color = Gw.Equipment.Colors[i];
        if (color) $("#Color").append(makeOption(i, Gw.Core.Translate(color)));
    }

    $("#SelectPrimary, #SelectSecondary").each(function() {
        for (var profession in Gw.Equipment.Professions)
            $(this).append(makeOption(profession, profession));
    }).change(function() {
        var hidden = $("#" + $(this).attr("id").substr(6));
        hidden.val($(this).val());
        
        var primary = Gw.Equipment.Professions[$("#Primary").val()];
        var secondary = Gw.Equipment.Professions[$("#Secondary").val()];
        
        if (!primary)
        {
            $("#EquipmentDetail").hide("slow");
            return;
        }
    
        $("#EquipmentDetail").fadeOut("fast", function() {
            window.AutomaticTemplateGeneration = false;

            resetDetails();

            addInsignias(primary.Insignias);

            for (var attribute in primary.Attributes) {
                addWeaponAttribute(attribute);
                addRuneAttribute(attribute);
            }

            if (secondary && secondary != primary) {
                for (var attribute in secondary.Attributes) {
                    addWeaponAttribute(attribute);
                }
            }
            
            generateTemplates();
            
            window.AutomaticTemplateGeneration = true;
            
            $("#EquipmentDetail").fadeIn("fast");
        });
    });

    $("#ProcessSkillTemplate").click(function() {

        $("#EquipmentDetail").fadeOut("fast", function() {

            window.AutomaticTemplateGeneration = false;

            resetDetails();

            var code = $("#SkillTemplate").val();
            var skillTemplate = new Gw.Skill.Template("Template", code);

            $("#Template").append(skillTemplate.toHtml({
                HideName: true,
                HideCode: true
            })).show();

            var primary = Gw.Equipment.Professions[Gw.Core.Professions[skillTemplate.PrimaryId]];
            var secondary = Gw.Equipment.Professions[Gw.Core.Professions[skillTemplate.SecondaryId]];

            if (!primary) return false;

            $("#Primary").val(primary.Name);
            $("#Secondary").val(secondary ? secondary.Name : "");

            var professions = primary.Name
            $("#Professions")

            addInsignias(primary.Insignias);

            var attributes = new Array();

            for (var attributeId in skillTemplate.AttributeIds) {
                var attributeName = Gw.Core.Attributes[attributeId];
                var attributeValue = skillTemplate.AttributeIds[attributeId]
                if (attributeValue <= 0) continue;
                
                attributes.push({
                    Name: attributeName,
                    Value: attributeValue,
                    IsPrimary: primary.Attributes[attributeName] ? true : false
                });
            }
            
            attributes.sort(function(a, b) {
                return b.Value - a.Value; // Sort on attribute points descending
            });

            var runeId = 0;

            for (var i in attributes)
            {
                var attribute = attributes[i];
                
                addWeaponAttribute(attribute.Name);

                if (attribute.IsPrimary)
                {
                    addRuneAttribute(attribute.Name);
                    if (runeId < 4)
                    {
                        $("#Rune" + runeId++).val("Minor " + attribute.Name + " Rune");
                    }
                }
            }
            
            generateTemplates();
            
            window.AutomaticTemplateGeneration = true;
            
            $("#EquipmentDetail").fadeIn("fast");
        });
    });
    
    if (Gw.Core.Tools.QueryString['template'])
    {
        $("#SkillTemplate").val(Gw.Core.Tools.QueryString['template'].replace(/\ /g, '+'));
        $("#ProcessSkillTemplate").click();
    }
});
